<template>
    <div class="container">
        <h1>基于深度学习的视频异常检测分析平台</h1>

        <!-- 上传区域 -->
        <!-- <el-card class="upload-section">
           <div> 
            <input type="file" ref="fileInput" @change="handleFileSelect" accept="video/*" style="display: none">
            <button plain @click="triggerFileSelect" class="upload-btn">
                <i class="el-icon-upload"></i> 选择视频文件
            </button>
            <div v-if="selectedFile" class="file-info">
                已选择文件: {{ selectedFile.name }}
                <el-progress v-if="uploadProgress > 0" :percentage="uploadProgress" status="success"
                    style="width: 300px; margin-top: 10px"></el-progress>
            </div>
            <button v-if="selectedFile && !uploading" @click="startUpload" class="analyze-btn">
                开始分析
            </button>
            </div> 
        </el-card> -->

        <!-- 上传区域 -->
        <el-card class="upload-section" shadow="hover">
            <el-row type="flex" align="middle" :gutter="20">
                <!-- 左侧文字 -->
                <el-col :span="12" class="left-text">
                    <div class="upload-label">
                        <i class="el-icon-video-camera-solid"></i>
                        <span>上传视频</span>
                        <div slot="tip" class="el-upload__tip">只能上传mp4文件，且不超过500MB</div>
                    </div>
                </el-col>

                <!-- 右侧操作区 -->
                <el-col :span="12" class="right-actions">
                    <input type="file" ref="fileInput" @change="handleFileSelect" accept="video/*"
                        style="display: none">

                    <!-- 横向排列容器 -->
                    <div class="action-row">
                        <!-- 文件选择按钮 -->
                        <el-button plain @click="triggerFileSelect" type="primary" icon="el-icon-upload"
                            class="select-btn">
                            选择视频文件
                        </el-button>

                        <!-- 文件信息展示 -->
                        <div v-if="selectedFile" class="file-info">
                            <el-tag type="info" class="file-tag" style="margin: 0 15px; max-width: 200px">
                                <i class="el-icon-document"></i>
                                {{ selectedFile.name }}
                            </el-tag>

                            <!-- 分析按钮 -->
                            <el-button v-if="!uploading" @click="startUpload" type="success" icon="el-icon-video-play"
                                class="analyze-btn">
                                开始分析
                            </el-button>
                        </div>
                    </div>

                    <!-- 进度条 (单独一行) -->
                    <el-progress v-if="uploadProgress > 0" :percentage="uploadProgress" :stroke-width="16"
                        status="success" class="progress-bar" style="margin-top: 10px"></el-progress>
                </el-col>
            </el-row>
        </el-card>

        <!-- 任务列表 -->
        <div class="task-list">
            <h2>分析任务列表</h2>
            <el-table :data="tasks" style="width: 100%">
                <el-table-column prop="taskId" label="任务ID" width="310"></el-table-column>
                <el-table-column label="状态" width="120">
                    <template slot-scope="scope">
                        <el-tag :type="statusType(scope.row.status)">
                            {{ scope.row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="filename" label="文件名" width="120"></el-table-column>
                <el-table-column prop="progress" label="处理进度" width="200">
                    <template slot-scope="scope">
                        <el-progress :percentage="scope.row.progress"></el-progress>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button v-if="scope.row.status === 'completed'" type="success" icon="el-icon-download"
                            @click="downloadResult(scope.row)">下载结果</el-button>
                        <el-button v-if="scope.row.status === 'completed'"
                            @click="showCompareView(scope.row)">对比展示</el-button>
                        <el-button v-if="scope.row.status === 'completed'" type="danger" icon="el-icon-warning"
                            @click="showAnalysisView(scope.row.taskId)">查看详情</el-button>
                        <el-button v-if="scope.row.status === 'failed'" type="danger" icon="el-icon-warning"
                            @click="showError(scope.row)">查看错误</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 对比展示区域 -->
        <div style="margin: 20px 0">
            <el-row type="flex" align="middle" :gutter="20">
                <!-- 左侧文字 -->
                <el-col :span="18" class="left-text">
                    <el-card shadow="hover">
                        <div slot="header" class="clearfix">
                            <i class="el-icon-document"></i>
                            <span>原始视频</span>
                        </div>
                        <div class="text item">
                            <VideoDetail :videoSrc="originalVideoUrl" />
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="18" class="left-text">
                    <el-card class="box-card">
                        <div slot="header" class="clearfix">
                            <i class="el-icon-document"></i>
                            <span>视频处理结果</span>
                        </div>
                        <div>
                            <v-if>
                                <el-progress :percentage="progress"></el-progress>
                            </v-if>
                            <v-else>
                                <VideoDetail :videoSrc="originalVideoUrl" />
                            </v-else>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>
        
        <!-- 在任务列表后添加对比展示区域 -->
        <div class="compare-section" v-if="showCompare">
            <VideoCompare :original-src="originalVideoUrl" :processed-src="processedVideoUrl" />
            <!-- <div class="control-bar">
                <el-button @click="playBoth">同时播放</el-button>
                <el-button @click="pauseBoth">同时暂停</el-button>
            </div> -->
        </div>

        <!-- 数据分析展示 -->
        <div v-if="showAnalysis">
            <VideoAnalysis :taskId="taskId" />
        </div>

        <!-- 错误对话框 -->
        <el-dialog title="错误详情" :visible.sync="errorDialogVisible">
            <div class="error-content">
                <pre>{{ currentError }}</pre>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import VideoCompare from './components/VideoCompare.vue'
import VideoAnalysis from './VideoAnalysis.vue';
import VideoDetail from './components/VideoDetail.vue';
import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:5000'

export default {
    components: { VideoCompare, VideoAnalysis, VideoDetail },
    data() {
        return {
            selectedFile: null,
            uploading: false,
            uploadProgress: 0,
            tasks: [],
            errorDialogVisible: false,
            currentError: '',
            pollIntervals: {},
            showCompare: false,
            originalVideoUrl: '',
            processedVideoUrl: '',
            showAnalysis: false,
            taskId: '',
        }
    },
    mounted() {
        // 初始化时加载本地存储的任务
        const savedTasks = localStorage.getItem('videoTasks')
        if (savedTasks) {
            this.tasks = JSON.parse(savedTasks)
            // 恢复轮询
            this.tasks.forEach(task => {
                if (!['completed', 'failed'].includes(task.status)) {
                    this.startPolling(task.taskId)
                }
            })
        }
    },
    methods: {
        showAnalysisView(taskId) {
            this.showAnalysis = true;
            this.taskId = taskId;
        },
        showCompareView(task) {
            console.log(task)
            this.originalVideoUrl = `http://localhost:5000/original_video/${task.taskId}`
            this.processedVideoUrl = `http://localhost:5000/processed_video/${task.taskId}`
            // this.processedVideoUrl = `http://localhost:9090/admin/system/file/204da308baca41cfab6224072e1f27af.mp4`
            this.showCompare = true
        },
        triggerFileSelect() {
            this.$refs.fileInput.click()
        },
        handleFileSelect(e) {
            const files = e.target.files
            if (files.length > 0) {
                this.selectedFile = files[0]
            }
        },
        async startUpload() {
            if (!this.selectedFile) return

            this.uploading = true
            const formData = new FormData()
            formData.append('file', this.selectedFile)

            try {
                const response = await axios.post('/upload', formData, {
                    onUploadProgress: progressEvent => {
                        this.uploadProgress = Math.round(
                            (progressEvent.loaded * 100) / progressEvent.total
                        )
                    }
                })

                const taskData = {
                    taskId: response.data.task_id,
                    filename: this.selectedFile.name,
                    status: 'pending',
                    downloadUrl: response.data.download_url
                }

                this.tasks.unshift(taskData)
                this.saveTasks()
                this.startPolling(taskData.taskId)

                this.$message.success('文件上传成功，开始分析处理')
            } catch (error) {
                this.$message.error(`上传失败: ${error.message}`)
            } finally {
                this.uploading = false
                this.uploadProgress = 0
                this.selectedFile = null
            }
        },
        startPolling(taskId) {
            if (this.pollIntervals[taskId]) return

            this.pollIntervals[taskId] = setInterval(async () => {
                try {
                    const response = await axios.get(`/status/${taskId}`)
                    const task = this.tasks.find(t => t.taskId === taskId)
                    console.log(response.data)
                    if (task) {
                        task.status = response.data.status

                        if (response.data.status === 'processing') {
                            task.progress = response.data.progress
                            // const progress = (data.current / data.total) * 100
                            // updateProgressBar(progress) // 更新进度条
                            // this.percentage = response.data.progress
                        }

                        if (response.data.status === 'completed') {
                            clearInterval(this.pollIntervals[taskId])
                            task.progress = response.data.progress
                            delete this.pollIntervals[taskId]
                            this.$message.success('分析处理完成')
                        }

                        if (response.data.status === 'failed') {
                            clearInterval(this.pollIntervals[taskId])
                            delete this.pollIntervals[taskId]
                            task.error = response.data.error
                            this.$message.error('处理失败')
                        }

                        this.saveTasks()
                    }
                } catch (error) {
                    console.error('轮询错误:', error)
                }
            }, 3000) // 每3秒轮询一次
        },
        statusType(status) {
            switch (status) {
                case 'completed': return 'success'
                case 'failed': return 'danger'
                default: return 'info'
            }
        },
        downloadResult(task) {
            console.log(task)
            window.open(`http://localhost:5000${task.downloadUrl}`, "_blank")
        },
        showError(task) {
            this.currentError = task.error || '未知错误'
            this.errorDialogVisible = true
        },
        saveTasks() {
            localStorage.setItem('videoTasks', JSON.stringify(this.tasks))
        }
    }
}
</script>

<style scoped>
.container {
    text-align: center;
    max-width: 1200px;
    margin: 20px auto;
    padding: 20px;
}

/* 添加在VideoDetect.vue的style部分 */
.compare-section {
    margin-top: 40px;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 8px;
}

.control-bar {
    margin-top: 20px;
    text-align: center;
}

.upload-section {
    border: 2px dashed #eee;
    padding: 30px;
    text-align: center;
    margin-bottom: 40px;
    border-radius: 8px;
}

.upload-btn {
    background: #409EFF;
    color: white;
    padding: 12px 24px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
}

.analyze-btn {
    background: #67C23A;
    color: white;
    padding: 12px 24px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-left: 20px;
}

.file-info {
    margin-top: 15px;
    color: #666;
}

.task-list {
    margin-top: 40px;
}

.error-content {
    background: #f8f8f8;
    padding: 15px;
    border-radius: 4px;
    max-height: 400px;
    overflow: auto;
}

pre {
    white-space: pre-wrap;
    word-wrap: break-word;
}
</style>